<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/7
 * Time: 18:01
 */
namespace App\Api\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Music;
use App\Models\MusicSearchLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\MusicBackground;

class MusicController extends Controller
{
    /**
     * @desc 获取背景音乐列表
     * @return array
     */
    public function get_background_music_list()
    {
        $page_size = IT('pagesize', 20);
        $where_arr = ['is_delete' => 0, 'status' => 1];
        $fields = ['id','music_name', 'music_link as music_like', 'id as template_id','time_length'];
        $music_list = MusicBackground::where($where_arr)->select($fields)->orderBy('id','asc')->paginate($page_size);
        foreach($music_list->items() as &$music) {
            $music->music_like = !empty($music->music_like) ? getSignUrl($music->music_like) : null;
        }

        return json_success('ok', ['total'=>$music_list->total(),'totalPage' => $music_list->lastPage(), 'list' => $music_list->items()]);
    }

    /*
     * 搜索音乐
     * */
    public function search(Request $request)
    {
        $keyword = IT('keyword', true, '搜索关键字必填', 10264);
        $page_size = IT('pagesize', 10);
        $feild = ['id','music_name', 'music_link', 'time_length'];
        $where_arr[] = ['status', '=', 0];
        $where_arr[] = ['is_delete', '=', 0];
        $where_arr []= ['music_name', 'like', "%{$keyword}%"];
        $music_list = Music::select($feild)->where($where_arr)->orderBy('sort', 'asc')->orderBy('number', 'desc')->orderBy('id','asc')->paginate($page_size);

        // 记录搜索日志
        if(empty($music_list->items())){
            $model = new MusicSearchLog();
            $model->keyword = $keyword;
            $model->save();
        }

        $data = null;
        if(!empty($music_list)){
            foreach($music_list->items() as &$music) {
                $music->music_link = !empty($music->music_link) ? getSignUrl($music->music_link) : null;
            }
        }
        return json_success('ok', ['total'=>$music_list->total(),'totalPage' => $music_list->lastPage(), 'list' => empty($music_list->items()) ? null : $music_list->items()]);
    }

}